import React, { useEffect } from 'react'
import G6 from '@antv/g6'
import { data } from './config'

let graph
const AntVTree = () => {
  useEffect(() => {
    createMyG6()
  }, [])
  const createMyG6 = () => {
    graph = new G6.TreeGraph({
      container: 'container',
      width: 800,
      height: 800,
      modes: {
        default: [
          {
            type: 'collapse-expand',
            onChange: function onChange(item, collapsed) {
              const data = item.getModel()
              data.collapsed = collapsed
              return true
            },
          },
          'drag-canvas',
          'zoom-canvas',
          {
            type: 'drag-node',
          },
        ],
      },
      defaultNode: {
        // size: [260, 80],
        type: 'circle',
      },
      defaultEdge: {
        type: 'cubic-vertical',
        style: {
          endArrow: true,
        },
      },
      layout: {
        type: 'compactBox',
        direction: 'TB',
        getId: function getId(d) {
          return d.id
        },
        getHeight: function getHeight() {
          return 16
        },
        getWidth: function getWidth() {
          return 16
        },
        getVGap: function getVGap() {
          return 80
        },
        getHGap: function getHGap() {
          return 20
        },
      },
    })
    // 设置各个节点样式及其他配置，以及在各个状态下节点的 KeyShape 的样式。
    // 提示: 该方法必须在 render 之前调用，否则不起作用。
    graph.node(function (node) {
      let position = 'right'
      let rotate = 0
      if (!node.children) {
        position = 'bottom'
        rotate = Math.PI / 2
      }

      return {
        label: node.id,
        labelCfg: {
          position,
          offset: 5,
          style: {
            rotate,
            textAlign: 'start',
          },
        },
        icon: {
          show: true,
          img:
            node.img ||
            'https://gw.alipayobjects.com/zos/basement_prod/012bcf4f-423b-4922-8c24-32a89f8c41ce.svg',
        },
      }
    })

    graph.data(data)
    // render就是更新布局,渲染数据,生产图表
    graph.render()
    // 更新布局后要自适应窗口
    graph.fitView()
  }

  return (
    <div>
      <button
        onClick={() => {
          graph.updateLayout({
            type: 'dendrogram',
          })
        }}
      >
        更改布局
      </button>
      <div id="container"></div>
    </div>
  )
}

export default AntVTree
